package com.ruoyi.wechat.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wechat.core.WxCore;
import com.ruoyi.wechat.domain.WxCampUser;
import com.ruoyi.wechat.domain.WxLoginUser;
import com.ruoyi.wechat.service.IWxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 微信登录服务实现
 * @auth zhaoly
 * @date 2024-01-25 10:24
 */
@Service
public class WxLoginService implements IWxLoginService {

    @Value("${wechat.userType}")
    private String userType;
    @Value("${wechat.wxUser}")
    private String wxUser;


    @Value("${wechat.wxUserRole}")
    private String wxUserRole;

    @Autowired
    private WxCore core;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private com.ruoyi.wechat.service.impl.WxCampUserServiceImpl campUserService;

    @Autowired
    private ISysUserService userService;

    /**
     * 微信登录
     * @param code 小程序预登录coce
     * @param userName 学号/工号/手机号
     * @param password 登录密码
     * @return 登录用户
     */
    @Override
    public WxLoginUser login(String code, String userName, String password){

        //请求wx后台通过code请求openid
        String openid = core.getOpenId(code);

        //String openid = code;

        //获取不到openid直接返回
        if(StringUtils.isBlank(openid)){
            return new WxLoginUser(userName, "", -1, "获取openid失败");
        }
        //通过openid查询系统用户
        WxCampUser campUser = campUserService.selectWxCampUserByOpenId(openid);
        if (campUser == null) {
            register(openid);
        }
        campUser = campUserService.selectWxCampUserByOpenId(openid);
        if(campUser != null){
            SysUser sysUser = userService.selectUserById(Long.valueOf(wxUser));
            sysUser.setUserName(campUser.getUsername());
            sysUser.setNickName(campUser.getUserId());
            sysUser.setRoleId(Long.valueOf(wxUserRole));
            sysUser.setEmail(campUser.getOpenId());
            sysUser.setPhonenumber(campUser.getPhone());
            sysUser.setPassword(campUser.getPassword());

            WxLoginUser wxLoginUser = generatorLoginUser(sysUser);
            wxLoginUser.setUserId(campUser.getUserId());
            wxLoginUser.setOpenId(campUser.getOpenId());
            wxLoginUser.setImageUrl(campUser.getImageUrl());

            wxLoginUser.setPhone(campUser.getPhone());
            wxLoginUser.setUsername(campUser.getUsername());
            return wxLoginUser;
        }

        // 通过用户名密码查询系统用户
        // sysUser = campUserService.selectCampUserByUserName(userName);

        return new WxLoginUser(userName, "", -1, "用户名或密码不正确");
    }

    /**
     * 生成微信用户登录参数
     * @param user 系统用户
     * @return
     */
    private WxLoginUser generatorLoginUser(SysUser user){

//        LoginUser loginUser = new LoginUser();]
//        loginUser.setUser(sysUser);
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));


        String token = tokenService.createToken(loginUser);
        return new WxLoginUser(user.getUserName(), user.getUserName(), token);
    }



    /**
     * 新用户注册
     *
     * @param user 新注册用户实例
     * @return 注册结果
     */
    @Override
    public int updateUserInfo(WxCampUser user) {

        WxCampUser sysUser = campUserService.selectWxCampUserByUserId(user.getUserId());
        if(sysUser == null){
            return -2;
        }
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        return campUserService.updateWxCampUser(user);
    }
    @Override
    public int register(String openid) {
        //获取不到openid直接返回
        if(StringUtils.isBlank(openid)){
            return -1;
        }

        WxCampUser user = new WxCampUser();
        user.setOpenId(openid);
        //通过openid查询系统用户
        WxCampUser sysUser = campUserService.selectWxCampUserByOpenId(openid);
        if(sysUser != null){
            return -2;
        }
        user.setUserId(IdUtils.randomUUID());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        return campUserService.insertWxCampUser(user);
    }


}